import { createRouter, createWebHistory } from 'vue-router'
import HomeView from '../views/HomeView.vue'
import LoginView from '@/views/LoginView.vue'
import UserView from '@/views/system/UserView.vue'
import RoleView from '@/views/system/RoleView.vue'
import RouterView from '@/views/system/RouterView.vue'
import PermissionView from '@/views/system/PermissionView.vue'
import { useGlobalStore } from '@/stores/global'
import { Message } from '@arco-design/web-vue'
import IndexView from '@/views/system/IndexView.vue'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/login',
      name: 'login',
      component: LoginView
    },
    {
      path: '/',
      name: 'home',
      component: HomeView,
      children: [
        { path: '', name: 'index', component: IndexView }
      ]
    }
    // {
    //   path: '/about',
    //   name: 'about',
    //   // route level code-splitting
    //   // this generates a separate chunk (About.[hash].js) for this route
    //   // which is lazy-loaded when the route is visited.
    //   component: () => import('../views/AboutView.vue')
    // }
  ]
})

router.beforeEach((to, from, next) => {
  //登录页
  if (to.path == '/login') {
    localStorage.clear()
    next()
    return
  }

  //判断token是否存在
  if (!localStorage.getItem('token')) {
    Message.error('当前未登录请先登录！')
    localStorage.clear()
    //不存在token
    next({ path: '/login', replace: true })
    return
  }

  //下一步
  next()
})

//添加路由
export const addRouter = (routers: any[]) => {
  //清除所有路由
  router.clearRoutes()

  //添加两个关键无关路由
  router.addRoute({ path: '/login', name: 'login', component: LoginView })
  router.addRoute({ path: '/', name: 'home', component: HomeView })
  router.addRoute('home', { path: '', name: 'index', component: IndexView })

  routers.forEach((value) => {

    //如果是层级菜单则不添加
    if (value.isMenu) return

    //添加到路由中
    router.addRoute('home', {
      path: value.uri,
      name: value.name,
      component: () => import((`../views/${value.path}`))
    })
  })
}

export default router
